package com.hmyd.hmyd_android.fragment;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import com.google.common.reflect.TypeToken;
import com.google.gson.Gson;
import com.hmyd.hmyd_android.R;
import com.hmyd.hmyd_android.AppBasic;
import com.hmyd.hmyd_android.adapter.InvestmentBillListAdapter;
import com.hmyd.hmyd_android.commons.UrlConstant;
import com.hmyd.hmyd_android.dto.Investment;
import com.hmyd.hmyd_android.dto.Page;
import com.hmyd.hmyd_android.ui.TicketsDetailsActivity;
import com.hmyd.hmyd_android.view.listview.XListView;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;

import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;

/**
 * 我要投资（票据）
 */
public class InvestmentBillFragment extends BasicFragmentList implements OnItemClickListener {
	private XListView mList;
	private View bill_background;
	private View bill_root;
	View root;
	
	private final int REFRESH = 1;
	private final int LOADMORE = 2;
	private final int INVESTMENT = 3;
	
	// 判断是否加载更多
	protected boolean hasMore = false;
	private String cursorId;
	
	InvestmentBillListAdapter adapter;
	
	// 数据信息
	private List<Investment> listData = new ArrayList<Investment>();
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		if (root == null) {
			root = inflater.inflate(R.layout.fragment_bill_investment, container, false);
			mList = (XListView) root.findViewById(R.id.list);
			
			bill_root = root.findViewById(R.id.bill_root);
			bill_background = root.findViewById(R.id.bill_background);
		}
		
		//缓存的rootView需要判断是否已经被加过parent， 如果有parent需要从parent删除，要不然会发生这个rootview已经有parent的错误。
		ViewGroup parent = (ViewGroup) root.getParent();
		if (parent != null) {
			parent.removeView(root);
		} 
		
		return root;
	}
	
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		
		setParams();
		
		setStyle(false);
		
		timer.start();
		
		onRequest(REFRESH, UrlConstant.PERSONALNOTESL, HttpMethod.GET, null);
	}
	
	/**
	 * 设置布局样式
	 * @param bol
	 */
	private void setStyle(boolean bol){
		if (bol) {
			bill_root.setBackgroundColor(getResources().getColor(R.color.white));
			mList.setVisibility(View.GONE);
			bill_background.setVisibility(View.VISIBLE);
		} else {
			bill_root.setBackgroundColor(getResources().getColor(R.color.gray_bg));
			mList.setVisibility(View.VISIBLE);
			bill_background.setVisibility(View.GONE);
		}
	}
	
	@Override
	public XListView getXList() {
		return mList;
	}
	
	private void setParams(){
		mList.setPullRefreshEnable(true); // 允许下拉刷新
		mList.setPullLoadEnable(false); // 禁止加载更多
		mList.setAutoLoadEnable(false); // 禁止自动加载
		mList.setXListViewListener(this);// 加载监听
		
		adapter = new InvestmentBillListAdapter(getActivity(), listData);
		
		mList.setOnItemClickListener(this);
		
		mList.setAdapter(adapter);
	}
	
	@Override
	public void onResume() {
		super.onResume();
		
		if (isLoading && listData.size() == 0) {
			onRequest(REFRESH, UrlConstant.PERSONALNOTESL, HttpMethod.GET, null);
		}
		
	}
	
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
	}

	private String result;
	
	@Override
	public void onPostSuccess(int postId, String result) {
		super.onPostSuccess(postId, result);
		
		// 防止多次加载重复数据
		if (!TextUtils.isEmpty(this.result) && this.result.equals(result)) {
			
			Log.i(" this.result ", " ------->>>>> result rep");
			return;
		}
		
		this.result = result;
		
		Gson gson = new Gson();
		java.lang.reflect.Type type2 = new TypeToken<Page<Investment>>() {}.getType();
		Page<Investment> page = gson.fromJson(result, type2);
		hasMore = page.hasMore;
		if(page!=null && page.records !=null && page.records.size() > 0){
			setStyle(false);
			
			for(int i=0;i<page.records.size();i++){
				Investment investment = page.records.get(i);
				if(AppBasic.ServerTime<investment.startTime){
					investment.countDownTimer = investment.startTime-AppBasic.ServerTime;
					
					page.records.remove(i);
					page.records.add(i, investment);
				}
			}
			
			switch (postId) {
			case REFRESH:
				listData.clear();
				listData.addAll(page.records);
				break;
			case LOADMORE:
				listData.addAll(page.records);
				break;
			default:
				break;
			}
			
			if(listData.size()>0){
				cursorId = listData.get(listData.size()-1).cursorId;
			}else{
				cursorId = null;
			}
			
			adapter.notifyDataSetChanged();
		} else {
			setStyle(true);
		}
		
		if(getXList()!=null && hasMore){
			getXList().setPullLoadEnable(true);
		}else if(getXList()!=null && !hasMore){
			getXList().setPullLoadEnable(false);
		}
		
	}

	@Override
	public void onPostFailure(int postId, String msg) {
		super.onPostFailure(postId, msg);
		
		if(getXList()!=null && hasMore){
			getXList().setPullLoadEnable(true);
		}else if(getXList()!=null && !hasMore){
			getXList().setPullLoadEnable(false);
		}
	}
	
	@Override
	public void onRefresh() {
		super.onRefresh();
		
		onRequest(REFRESH, UrlConstant.PERSONALNOTESL, HttpMethod.GET, null);
	}
	
	@Override
	public void onLoadMore() {
		super.onLoadMore();
		
		RequestParams params = new RequestParams();
		params.addBodyParameter("lastCursor", cursorId);
		
		onRequest(LOADMORE, UrlConstant.PERSONALNOTESL, HttpMethod.POST, params);
	}
	
	CountDownTimer timer = new CountDownTimer(1000*60*60*24,1000) {
	       @Override

	       public void onTick(long millisUntilFinished) {
	    	   for(int i=0;i<listData.size();i++){
					Investment investment = listData.get(i);
					if(investment.countDownTimer>=1000){
						investment.countDownTimer = investment.countDownTimer-1000;
						
						listData.remove(i);
						listData.add(i, investment);
					}else{
						investment.countDownTimer = 0;
						
						listData.remove(i);
						listData.add(i, investment);
					}
				}
	    	   
	    	   adapter.notifyDataSetChanged();
	       }

	       @Override
	       public void onFinish() {

	       }

	    };
	
	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
//		Investment investment  =(Investment)parent.getAdapter().getItem(position);
		
		startActivity(TicketsDetailsActivity.getIntent(getActivity(),
				(Investment)parent.getAdapter().getItem(position)));
	}
	
	@Override
	public void onDestroy() {
		super.onDestroy();
				
		result = null;
	}
	
	public void onDetach() {
		super.onDetach();
		try {
			Field childFragmentManager = Fragment.class
					.getDeclaredField("mChildFragmentManager");
			childFragmentManager.setAccessible(true);
			childFragmentManager.set(this, null);

		} catch (NoSuchFieldException e) {
			throw new RuntimeException(e);
		} catch (IllegalAccessException e) {
			throw new RuntimeException(e);
		}
	}
	
	@Override
	public void onDestroyView() {
		super.onDestroyView();
		
		if (this != null) {
			FragmentManager mManager = getFragmentManager();
			if(mManager != null && !mManager.isDestroyed()){
				final FragmentTransaction mTransaction = mManager.beginTransaction();
				if(mTransaction != null){
					mTransaction.remove(this).commit();
				}
			}
		}
	}
}
